package com.game.service.comm;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

public class RSAUtils {


    public static String base64PublicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCj8R7Frm9AgyRhm8pmPhvoIzA+eejxBj60MuQYRbeNrLRF0IpqI8b0kl4IWsg+L1rHbiG5EA3AB7fEkdBf2HflwlTLtc4PJOqlL9sPBY16tMYgL4FbejutyQytZp9tCzKrz1h0ImU2REhSsXpZTtC+PIFo3MJLJYedsyCiKs0IKwIDAQAB";
    public static String base64PrivateKey = "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAKPxHsWub0CDJGGbymY+G+gjMD556PEGPrQy5BhFt42stEXQimojxvSSXghayD4vWsduIbkQDcAHt8SR0F/Yd+XCVMu1zg8k6qUv2w8FjXq0xiAvgVt6O63JDK1mn20LMqvPWHQiZTZESFKxellO0L48gWjcwkslh52zIKIqzQgrAgMBAAECgYB4rZtLRNYcFO0I9NcOYBXG0XBH7RFtqn0pxHRm8ZrmLQUehx38d42SptOVLs5MCCu4tfcY9RpKCuRZTESo6P2H8suFxQqyuNVIcg5JIAFDRnTqBRuz9mEl9JaNcP+3CV2GOnQO/lvcj/CHyeNbDsGgpMAsJXFYlv6wwH4lA6BPUQJBAN8TAUUjAr3InO/6JvmuvnIzf9/c7fAZbtuvEP0/fzVAnAPIbgJul3TXshMtZAkEsRBPYAX2c5liaP5kkffaXkcCQQC8I8NeZoKKWO1kIRPzkxFAcEIeg/Tgzjg7UQ4ymszP/RSPgwaW8WTPegLJsRaWNZeGFaZyTY5LKi9O6D+b9UT9AkBTyMiWVhMGgx3myHbxGp/vNsaVp1466uKHYpan97xonO68QQCIq075lLYOm+LRvFBgxt9S/gDnIF49BjsI85yrAkBXIrUsdovFKZShCFTmPdoCnztwSKtUpw4SIuNRerKbLdqk8QlPRXPsR9UctsEARsfr2QEi9VqO43XPtO8o+zq9AkBuUR6fm1WPG65A6ReXVghC6ok0jnUzLZfpLKkJlzxxUZyaGIniPwo3YXviMZZaqnZlJB/BIeKPDmR+2E04+RXq";

    public static void main(String[] args) {
        try {
            createKeyPair();

            //   System.out.printf("===PublicKey:%s,PrivateKey:%s\n", publicKey, privateKey.getEncoded());

            //String originalData = "{\"sign\":\"13f32343c59a3ed77ec07ed3fc68812e\",\"result\":{\"os\":0,\"fee\":10000,\"uid\":10087,\"item\":2,\"prize\":0,\"ratio\":\"x1.95\",\"token\":\"token\",\"gameid\":10005,\"liveid\":-999,\"stream\":\"-9999_-9999\",\"remarks\":{\"fee\":10000,\"item\":2,\"betid\":9,\"isRed\":1,\"prize\":0,\"ratio\":\"x1.95\",\"score\":100000,\"orderid\":\"game_10005_20250818173857_P100000994\",\"prizeid\":2,\"deduction\":{\"coin\":0,\"diamond\":0},\"itemStatus\":0},\"deduction\":{\"coin\":0,\"diamond\":0},\"tableType\":1},\"addtime\":1755509988250,\"orderid\":\"game_10005_20250818173857_P100000994\"}";

            String originalData = "zTA5uyXga/al2WOHvPXGnQ==";
            System.out.println("Original Data: " + originalData.length() + "," + originalData);

            byte[] encrypt = encrypt(originalData);
            String Encrypted = Base64.getEncoder().encodeToString(encrypt);
            System.out.println("Encrypted Data: " + Encrypted);
//
//            // 使用私钥解密数据

            // 将Base64编码的私钥字符串解码为字节数组
            byte[] encrypt2 = Base64.getDecoder().decode(Encrypted);

            String decryptedData = decrypt(encrypt2);

            System.out.println("Decrypted Data: " + decryptedData);


        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static Cipher cipherPrivate;//私钥加密器
    private static Cipher cipherPublic;//公钥解密器

    // 生成RSA密钥对
    private static KeyPair generateKeyPair() throws NoSuchAlgorithmException {
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        keyGen.initialize(1024); // 密钥长度
        return keyGen.generateKeyPair();
    }

    // 初始公钥加密器
    public static Cipher initCipherPublic() throws Exception {
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        byte[] decodedPublicKey = Base64.getDecoder().decode(base64PublicKey);
        X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(decodedPublicKey);
        PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);

        cipherPublic = Cipher.getInstance("RSA");
        cipherPublic.init(Cipher.ENCRYPT_MODE, publicKey);
        return cipherPublic;

    }

    // 使用公钥加密数据
    public static byte[] encrypt(String data) throws Exception {
        if (cipherPublic == null) {
            cipherPublic = initCipherPublic();
        }
        return cipherPublic.doFinal(data.getBytes());
    }


    // 初始私钥解密器
    public static Cipher initCipherPrivate() throws Exception {
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        byte[] decodedPrivateKey = Base64.getDecoder().decode(base64PrivateKey);
        PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(decodedPrivateKey);
        PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);

        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        return cipher;
    }

    public static String decrypt(byte[] encryptedData) throws Exception {
        if (cipherPrivate == null) {
            cipherPrivate = initCipherPrivate();
        }
        byte[] decryptedBytes = cipherPrivate.doFinal(encryptedData);
        return new String(decryptedBytes);
    }


    public static void createKeyPairString() {
        // 生成RSA密钥对
        KeyPair keyPair = null;
        try {
            keyPair = generateKeyPair();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
        // 将公钥和私钥转换为字节数组以便保存
        byte[] encodedPublicKey = keyPair.getPublic().getEncoded();
        byte[] encodedPrivateKey = keyPair.getPrivate().getEncoded();

        // 将公钥和私钥编码为Base64字符串格式以方便保存
        String publicKeyString = Base64.getEncoder().encodeToString(encodedPublicKey);
        String privateKeyString = Base64.getEncoder().encodeToString(encodedPrivateKey);

        System.out.println(publicKeyString.length() + "," + publicKeyString);
        System.out.println(privateKeyString.length() + "," + privateKeyString);

    }

    /***
     * 将公钥,私钥还原成
     */
    public static void createKeyPair() {
        try {
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            // 将Base64编码的公钥字符串解码为字节数组
            byte[] decodedPublicKey = Base64.getDecoder().decode(base64PublicKey);
            X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(decodedPublicKey);
            PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);

            // 将Base64编码的私钥字符串解码为字节数组
            byte[] decodedPrivateKey = Base64.getDecoder().decode(base64PrivateKey);
            PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(decodedPrivateKey);
            PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);

            // 创建KeyPair对象
            KeyPair restoredKeyPair = new KeyPair(publicKey, privateKey);

            // 输出密钥信息（仅用于验证）
            System.out.println("Restored Public Key Algorithm: " + restoredKeyPair.getPublic().getAlgorithm());
            System.out.println("Restored Private Key Algorithm: " + restoredKeyPair.getPrivate().getAlgorithm());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}